package cn.anc.aonicardv.module.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.event.DestroyMapEvent;
import cn.anc.aonicardv.event.HideBottomTabEvent;
import cn.anc.aonicardv.event.UpdateWifiName;
import cn.anc.aonicardv.module.ui.album.AlbumFragment;
import cn.anc.aonicardv.module.ui.base.BaseActivity;
import cn.anc.aonicardv.module.ui.recorder.RecorderFragment;
import cn.anc.aonicardv.util.DeviceUtils;
import cn.anc.aonicardv.util.GpsUtil;
import cn.anc.aonicardv.util.NetUtils;
import cn.anc.aonicardv.util.StringUtils;
import cn.anc.aonicardv.util.WiFiUtil;
import rx.Subscription;

//import cn.anc.aonicardv.bean.ResponseBean;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private WifiStateReceiver wifiStateReceiver;
    public Subscription s;
    private IntentFilter intentFilter;
    private FragmentManager fragmentManager;
    private RadioGroup mRadioGroup;
    private RadioButton mRadioBtnRecorder, mRadioBtnAlbum;

    /** Fragment TAG :  记录仪 */
    public static final String FRAGMENT_TAG_RECORDER = "fragment_tag_recorder";

    /** Fragment TAG :  本地相册 */
    public static final String FRAGMENT_TAG_ALBUM = "fragment_tag_album";

    /** Fragment TAG数组 */
    private static final String[] mFragmentTags = new String[]{FRAGMENT_TAG_RECORDER, FRAGMENT_TAG_ALBUM};
    /** Fragment : 记录仪 */
    private RecorderFragment mFragmentRecorder;
    /** Fragment :  本地相册 */
    private AlbumFragment mFragmentAlbum;
    private RelativeLayout mLayoutBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        fragmentManager = getSupportFragmentManager();
        MyApplication.needAutoConnect = true;
        initView();
        initWifi();
        MyApplication.IP = null;
        registerReceiver(wifiStateReceiver, intentFilter);
    }

    private void initView() {
        mLayoutBottom = (RelativeLayout) findViewById(R.id.layout_main_bottom);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_tabs);
        mRadioBtnRecorder = (RadioButton) findViewById(R.id.tab_recorder);
        mRadioBtnAlbum = (RadioButton) findViewById(R.id.tab_album);
        mRadioGroup.setOnCheckedChangeListener(this);
        initDefaultDisplayFragment();
    }

    /** 初始化默认显示的fragment */
    private void initDefaultDisplayFragment() {
        String tag = getIntent().getStringExtra(Constant.KEY_INTENT_JUMP_BASE_DATA);
        int id;
        if (FRAGMENT_TAG_ALBUM.equals(tag)) {
            id = R.id.tab_album;
        } else {
            id = R.id.tab_recorder;
        }
        mRadioGroup.check(id);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(fragmentManager, transaction);
        switch (checkedId) {
            case R.id.tab_recorder:// 切换到记录仪
                mRadioBtnRecorder.setChecked(true);
                if (mFragmentRecorder == null) {
                    mFragmentRecorder = new RecorderFragment();
                    transaction.add(R.id.layout_fragment_content, mFragmentRecorder, FRAGMENT_TAG_RECORDER);
                }
                transaction.show(mFragmentRecorder);

                break;

            case R.id.tab_album:// 切换到本地相册
                mRadioBtnAlbum.setChecked(true);
                if (mFragmentAlbum == null) {
                    mFragmentAlbum = new AlbumFragment();
                    transaction.add(R.id.layout_fragment_content, mFragmentAlbum, FRAGMENT_TAG_ALBUM);
                }
                transaction.show(mFragmentAlbum);
                break;
        }
        transaction.commit();
    }

    /** 隐藏所有的fragment */
    private void hideFragments(FragmentManager fragmentManager, FragmentTransaction transaction) {
        for (String fragmentTag : mFragmentTags) {
            Fragment fragment = fragmentManager.findFragmentByTag(fragmentTag);
            if (fragment != null && fragment.isVisible()) {
                transaction.hide(fragment);
            }
        }
        mRadioBtnRecorder.setChecked(false);
        mRadioBtnAlbum.setChecked(false);
    }

    private void initWifi() {
        wifiStateReceiver = new WifiStateReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    }



    @Override
    protected void onResume() {
        super.onResume();
        getWifiInfo(this,false);

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

   private String mDefaultIp = "192.168.42.1";
   private void getWifiInfo(Context context, boolean isReceiver) {
       StringUtils.printLog("getWiFiInfo:"," onReceive  :"+isReceiver);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1 && !GpsUtil.isOPen(MainActivity.this)) {
            return;
        }
       String mCurrentSSID = NetUtils.getWIFISSID(context);
       if (DeviceUtils.isLingKeDevices(mCurrentSSID)){
           //当前连接的是记录仪
           EventBus.getDefault().post(new UpdateWifiName(false, NetUtils.getWIFISSID(context), mDefaultIp, isReceiver));
       }else{
           EventBus.getDefault().post(new UpdateWifiName(false, null, null, isReceiver));
       }

    }

    @Override
    public void initVariable() {
    }

    @Override
    public void setListener() {

    }

    @Override
    public void initData() {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HideBottomTabEvent event) {
        if (event.isHide) {
            mLayoutBottom.setVisibility(View.GONE);
        } else
            mLayoutBottom.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(wifiStateReceiver);
        EventBus.getDefault().post(new DestroyMapEvent());
        EventBus.getDefault().unregister(this);
    }




    public class WifiStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getWifiInfo(context, true);
        }
    }

    private long lastTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastTime > 1500) {
                Toast.makeText(this, getString(R.string.exit_hint), Toast.LENGTH_SHORT).show();
                lastTime = System.currentTimeMillis();
                return true;
            }
        }
        finish();
        if (NetUtils.isConnectedDevices(this)) {
            WiFiUtil.getInstance(this).closeWifi();
        }

        return true;
    }


}
